#! /usr/bin/env python """ This file intended to be used within an interactive instruction session It also happens to be an example of bad programming style yet useful for a training session. """ VERBOSE = True #VERBOSE = None class Breakfast2: serving = None skipping = None ordered = None def __init__(self): self.serving = ["spam & eggs", "toast"] self.skipping = [] if VERBOSE: print """ Avoid subtle Python behavior: avoiding data sharing Multiple instances of a class may avoid sharing of data by assigning values "on demand" within any method, such as the constructor. """ alice = Breakfast2() bob = Breakfast2() if VERBOSE: print """ Now, they still have identical content... """ if bob.serving == alice.serving: print "Yes. Both Bob and Alice have identical VALUES." else: print "No. Bob and Alice have different values." if VERBOSE: print """ Each references a DIFFERENT object! """ if bob.serving is alice.serving: print "Yes. Both Bob and Alice REFERENCE the SAME data." else: print "No. Bob and Alice REFERENCE DIFFERENT data." if VERBOSE: print """ Unlike when defined within class definition, these are no longer identical: """ bob.skipping.append("spam") print "Bob skipping:", bob.skipping print "Alice skipping:", alice.skipping if VERBOSE: print """ As with the example of creating class attributes "on demand" this time, these were created with initial values of None. As a result, assigning one may be done without effecting the other. """ bob.ordered = 1 print "Bob ordered:", bob.ordered print "Alice ordered:", alice.ordered #End.